package com.gitee.core.dubbo.core;

import com.gitee.core.dubbo.DubboServiceException;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Component
public class ServiceDispacherImpl implements ServiceDispacher {
    /**
     * 服务调用
     */
    public CallResult invoke(Service service) {
        String serviceName = service.getService();

        Object object = null;
        try {
            object = SpringApplicationContext.getBean(serviceName);
        } catch (Exception ex) {

        }
        if (object == null) {
            throw new DubboServiceException("找不到该服务：" + serviceName);
        }

        String methodName = service.getService();
        Method[] methods = object.getClass().getMethods();
        Method method = null;
        for (Method met : methods) {
            if (met.getName().equals(methodName)) {
                method = met;
            }
        }
        if (method == null) {
            throw new DubboServiceException(methodName + "方法未定义");
        }

        Class<?>[] clses = method.getParameterTypes();
        Object result = null;
        try {
            CallParams params = new CallParams();
            if (clses.length == 0) {
                result = method.invoke(object, params);
            } else if (clses.length >= 1) {
                Class cls = clses[0];
                if (cls.getName().equals(CallParams.class.getName())) {
                    params.setData(service.getData());
                    result = method.invoke(object, params);
                } else {
                    result = method.invoke(object, params);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new DubboServiceException("调用异常");
        }

        CallResult sr = (CallResult) result;

        return sr;
    }
}
